package ru.reaperoq.taskmanager.models

import jakarta.persistence.*
import org.hibernate.annotations.CreationTimestamp
import ru.reaperoq.taskmanager.dto.TagResponse
import ru.reaperoq.taskmanager.toEpoch
import java.time.LocalDateTime

@Entity(name = "tags")
open class Tag(
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
    open val id: Long? = null,
    @Column(length = 50, nullable = false)
    open val title: String,
    @Column(updatable = false, insertable = false)
    @CreationTimestamp
    open val createdAt: LocalDateTime = LocalDateTime.now(),
    open val color: Int,

    @ManyToOne
    @JoinColumn(nullable = false)
    open val author: User,
    @ManyToMany(cascade = [CascadeType.ALL])
    @JoinTable(
        name = "tasks_to_tags",
        joinColumns = [JoinColumn(name = "task_id", referencedColumnName = "id")],
        inverseJoinColumns = [JoinColumn(name = "tag_id", referencedColumnName = "id")]
    )
    open val tasks: MutableSet<Task> = mutableSetOf(),
) {
    fun toResponse(): TagResponse =
        TagResponse(
            id = this.id!!,
            title = this.title,
            color = this.color,
            createdAt = this.createdAt.toEpoch()
        )
}